package cn.edu.nuc.film.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.nuc.film.entity.Order;
import cn.edu.nuc.film.entity.User;
import cn.edu.nuc.film.service.interfaces.OrderService;

@Controller
@RequestMapping(value="/film/order")
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	/**
	 * 获取用户的订单信息
	 * @param userid
	 * @return
	 */
	@RequestMapping(value="/orderList",method=RequestMethod.GET)
	public String orderList( Model model,HttpServletRequest request){
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		int userid = user.getUserid();
		
		/**
		 * 获取的order列表
		 */
		List<Order> list = orderService.list(userid);
		//order列表
		int listsize = list.size();
		model.addAttribute("list", list);
		model.addAttribute("listsize", listsize);
		/**
		 * order所有film票的总价
		 */
		
		//设置总价初始值
		int stprice = 0;
		
		for( int i=0;i<list.size();i++){
			
			int price = list.get(i).getFilmTprice();
			stprice = stprice + price;
			
		}
		
		//将获取的总价传到前台
		model.addAttribute("stprice", stprice);
		return "/page/order";
		
	}
	
	/**
	 * 生成订单，将购买的film信息添加发哦购物车里
	 * @param order
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/createOrder",method=RequestMethod.POST)
	public String creatOrder( Order order,Model model){
		
		int count = orderService.creatOrder( order );
		System.out.println(count);
		if( count > 0){
			
			return "redirect:orderList";
			
		}else{
			
			model.addAttribute("msg", "购买失败!");
			return "/page/store_shop";
		}
		
		
	}
	
	/**
	 * 退票，通过orderid来进行删除order里的记录
	 * @param orderid
	 * @return 
	 * @return
	 */
	@RequestMapping(value="/refund",method=RequestMethod.GET)
	public @ResponseBody Map<String, Object> refund( int orderid , Model model){
		Map<String,Object> map = new HashMap<>();
		int count = orderService.refund(orderid);
		if( count > 0){
			map.put("success", "退票成功!");
		}else{
			map.put("success", "删除失败!");
		}
		System.out.println(map);
		return map;
	}
	
}
